package com.example.demo.configuration.config;


import cn.hutool.Hutool;
import cn.hutool.json.JSONUtil;
import com.example.demo.common.MqttTopicEnum;
import com.example.demo.common.RedisUtil;
import com.example.demo.entity.TestingResultInfo;
import com.example.demo.service.TestingResultInfoService;
import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * mqtt客户端消息处理类
 * **/
@Slf4j
@Component
public class MqttReceiveHandle {

    @Resource
    private TestingResultInfoService testingResultInfoService;

    @Resource
    private RedisUtil redisUtil;

    public void handle(Message<?> message){
        log.info("主题：{}，QOS:{}，消息接收到的数据：{}", message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC), message.getHeaders().get(MqttHeaders.RECEIVED_QOS), message.getPayload());
        if (Objects.equals(message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC), "test/topic")){
            String messageToString = message.getPayload().toString();
            TestingResultInfo userFromJson = JSONUtil.toBean(messageToString, TestingResultInfo.class);
            if(redisUtil.hasKey(userFromJson.getQRCode())){
                return;
            };
            testingResultInfoService.saveTestingResult(userFromJson);
            redisUtil.setWithExpire(userFromJson.getQRCode(),userFromJson.getQRCode(),100);
        }
    }
}